<template>
  <div class="login" v-if="action === 'form'">
    <el-form ref="formRef" :inline="true" :model="form" :rules="loginRules" class="demo-form-inline">
      <el-form-item label="Username" prop="username">
        <el-input v-model="form.username" placeholder="Approved by" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitFn">Login</el-button>
      </el-form-item>
    </el-form>
  </div>
  <el-container v-if="action === 'list'" style="padding: 0px;margin: 0px;">
    <el-header style="padding: 0px;margin-top: 0px;">
      <div class="head-tab">
        <span style="margin-right: 20px;"> Logged in as </span>
        <span style="font-weight: 500;">{{ name }}</span>
      </div>
    </el-header>
    <el-main>
      <el-row justify="space-between">
        <el-col :span="2"><h2>Threads</h2></el-col>
        <el-col :span="2">
          <el-button type="primary"  :icon="Plus" @click="dialog = true">New thread</el-button>
        </el-col>
      </el-row>
      <el-table :data="threads" style="width: 100%">
        <el-table-column prop="thread_title" label="threadTitle">
          <template #default="scope">
            <el-popover :visible="popoverPost[scope.row.id]" :key="`thread_table_${scope.row.id}`" placement="right" :width="800" trigger="click">
              <template #reference>
                <el-link @click="showPost(scope.row.id)">{{ scope.row.thread_title }}</el-link>
              </template>
              <el-timeline>
                <el-timeline-item
                    v-for="(activity, index) in postes"
                    :key="index"
                    :timestamp="activity.timestamp"
                >
                  {{ activity.text }}
                  <span style="float: right;font-size: 12px;font-weight: 500;color: #bbb;">{{activity.name }}</span>
                </el-timeline-item>
                <div style="display: flex;width: 100%;align-content: space-between;">
                  <el-input v-model="postInput" style="width: 200px;margin-left: 50px;"></el-input>
                  <el-button v-loading="loading" @click="addPosts(scope.row.id)" style="margin-left: 50px;">Post</el-button>
                </div>
              </el-timeline>
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column prop="icon" label="icon"  />
        <el-table-column prop="user" label="user" />
        <el-table-column label="operation">
          <template #default="scope">
            <el-button v-loading="loading" size="small"  @click="deleteThreadBox(scope.row)" :icon="Delete">delete</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-main>
  </el-container>


  <el-dialog v-model="dialog" title="New Threads">
    <el-form ref="threadFormRef" :model="threadForm.v" :rules="threadRules">
      <el-form-item label="Thread title" :label-width="formLabelWidth" prop="thread_title">
        <el-input v-model="threadForm.v.thread_title" autocomplete="off" />
      </el-form-item>
      <el-form-item label="Icon" :label-width="formLabelWidth" prop="icon">
        <span style="margin-right: 10px;">{{ threadForm.v.icon }}</span>
        <el-popover :visible="popoverIcon"  placement="right" :width="400" trigger="click">
          <template #reference>
            <el-button size="small" style="margin-right: 16px" @click="popoverIcon = true">choose icon</el-button>
          </template>
          <el-collapse v-model="activeCard" accordion>
            <el-collapse-item v-for="(item,index) in emj" :name="index" :key="index"  :title="item.name">
              <span v-for="(ele,kIndex) in item.iconArr" :key="`v_${kIndex}`"
                    @click="chooseIcon(ele.icon)"
                    style="padding-left: 5px;cursor: pointer;"
              >{{ ele.icon}}</span>
            </el-collapse-item>
          </el-collapse>
        </el-popover>
      </el-form-item>
      <el-form-item label="Text" :label-width="formLabelWidth" prop="text">
        <el-input
            v-model="threadForm.v.text"
            :rows="4"
            type="textarea"
            placeholder="Please input Text"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button v-loading="loading" @click="cancelThreadForm">Cancel</el-button>
        <el-button type="primary" @click="submitThreadFn">
          Confirm
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import {reactive, ref} from "vue";
import request from "@/api/request";
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus,Delete } from '@element-plus/icons-vue'
import emojiArr from '/src/api/emoj'



const form = reactive({
  username: 'norman'
})

const action = ref('form')

const dialog = ref(false)

const formLabelWidth = 140

const popoverIcon = ref(false)

const loading = ref(false)


const activeCard = ref(['1'])


const emj = ref(emojiArr)
// console.info(emj.value)

const name = ref('Jeon')

const validatePass = (rule, value, callback) => {
  if (!/^[a-zA-Z]+$/.test(value)) {
    callback(new Error('The input must be English characters!'))
  } else{
    callback()
  }
}

// loginRole校验表单规则
const loginRules = reactive({
  username: [
    { required: true, trigger: 'blur', message: 'User name cannot be empty!' },
    { validator: validatePass, trigger: 'blur' }
  ],
})


// 轮询查询线程
const timing = ()=>{
  setInterval(()=>{
    queryThreads()
  },5000)
}

const formRef = ref()

const submitFn = function (){
  formRef.value.validate((valid) => {
    if (valid) {
      userInfoFn(form.username).then((rep)=>{
        name.value = rep.data.name
        action.value = 'list'
        queryThreads()
        timing()
      }).catch((e)=>{
        ElMessage.warning(e.response.data.error)
      })
    } else {
      console.log('error submit!!')
      return false
    }
  })
}

const userInfoFn = (username)=>{
  return request({
    url: '/api/users/'+username,
    method:'get',
  })
}

const threads = ref()
// 获取线程列表
const getTheadsFn = ()=>{
  return request({
    url: '/api/threads',
    method:'get',
  })
}

const queryThreads = ()=>{
  getTheadsFn().then((rep)=>{
    // threads.value = rep.data
    threads.value = rep.data
    changePopoverPost()
    // console.info(threads.value)
  })
}

// 开发创建线程对话框

const threadForm = reactive({v:{
    thread_title: null,
    user: form.username,
    text: null,
    icon: null
  }})

// 新增线程
const addThreads = async (data)=>{
  request({
    url: '/api/threads',
    method:'post',
    data
  }).then(()=>{
    // console.info(rep)
    ElMessage({
      type: 'info',
      message: 'Publish successfully',
    })
  })
}

// 删除对话框
const deleteThreadBox = (row) => {
  ElMessageBox.confirm(
      'Are you sure you want to delete the Thread ?',
      'Warning',
      {
        confirmButtonText: 'OK',
        cancelButtonText: 'Cancel',
        type: 'warning',
      }
  )
      .then(async () => {
        if (row.user !== form.username) {
          ElMessage({
            type: 'info',
            message: 'It cannot be deleted if it is not your own!',
          })
          return
        }
        await deleteThread(row)
        ElMessage({
          type: 'success',
          message: 'Delete success',
        })
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: 'Delete canceled',
        })
      })
}

// 删除线程
const deleteThread = async (row)=>{
  loading.value = true;
  request({
    url: `/api/threads/${row.id}`,
    method:'delete',
    data: {user: form.username}
  }).then(()=>{
    loading.value = false
    queryThreads()
    // console.info(rep)
  })
}

// 选中图标
const chooseIcon = (icon)=>{
  // console.info(icon)
  threadForm.v.icon = icon
  popoverIcon.value = false
}

// loginRole校验表单规则
const threadRules = reactive({
  thread_title: [
    { required: true, trigger: 'blur', message: 'Title cannot be empty!' },
  ],
  text: [
    { required: true, trigger: 'blur', message: 'text cannot be empty!' },
  ],
  icon: [
    { required: true, trigger: 'blur', message: 'icon cannot be empty!' }
  ],
})

// 清空线程表单
const clearThreadForm = ()=>{
  threadForm.v = {
    thread_title: null,
    user: form.username,
    text: null,
    icon: null
  }
}

// 取消新增线程表单
const cancelThreadForm = ()=>{
  dialog.value = false
  clearThreadForm()
}

// 提交thread表单
const threadFormRef = ref()
const submitThreadFn = function (){
  threadFormRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true
      await addThreads(threadForm.v)
      loading.value = false
      dialog.value = false
      queryThreads()
      clearThreadForm()
      console.info('submit')
    } else {
      console.log('error submit!!')
      return false
    }
  })
}

// 查询post
const postes = ref()
const qryPosts = (id)=>{
  request({
    url: `/api/threads/${id}/posts`,
    method:'get'
  }).then((rep)=>{
    // console.info(rep.data)
    postes.value = rep.data
  })
}

// 动态更新post弹出框
const popoverPost = ref({})

const changePopoverPost = ()=>{
  for (let ky in threads) {
    popoverPost[threads[ky].id] = false
  }
}

const showPost = (id)=>{
  qryPosts(id)
  popoverPost.value = true
}

// 新增 post
const postInput = ref()

const addPosts = (id)=>{
  const data = {
    user: form.username,
    text: postInput.value
  }
  // console.info(data)
  loading.value = true
  request({
    url: `/api/threads/${id}/posts`,
    method:'post',
    data
  }).then(()=>{
    // console.info(rep.data)
    qryPosts(id)
    postInput.value = ''
    loading.value = false
    // console.info(rep.data)
  })
}

</script>

<style>
.head-tab{
  display: flex;
  justify-content: flex-end;

}
.login {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>
